import os
from typing import Dict, Final, Literal, Optional

# 基础路径配置
LOG_DIR: Final[str] = os.getenv('UNIFIED_LOG_DIR', os.getenv('LOG_DIR', 'logs'))
LOG_FILE: Final[str] = os.getenv('UNIFIED_LOG_FILE', os.path.join(LOG_DIR, "app.log"))

# 日志文件配置
LOG_RETENTION_DAYS: Final[int] = int(os.getenv('LOG_RETENTION_DAYS', '7'))
LOG_MAX_FILE_SIZE: Final[str] = os.getenv('LOG_MAX_FILE_SIZE', '100MB')  # 支持 KB, MB, GB
LOG_BACKUP_COUNT: Final[int] = int(os.getenv('LOG_BACKUP_COUNT', '5'))

# 日志格式配置
LOG_FORMAT: Final[str] = os.getenv('LOG_FORMAT', 
    "[%(asctime)s] [%(levelname)s] [%(clean_filename)s.%(funcName)s:%(lineno)d] %(message)s")
DATE_FORMAT: Final[str] = os.getenv('DATE_FORMAT', "%Y-%m-%d %H:%M:%S")

# 日志级别配置
LOG_LEVELS: Final[Dict[str, int]] = {
    'DEBUG': 10,
    'INFO': 20,
    'WARNING': 30,
    'ERROR': 40,
    'CRITICAL': 50
}

# 控制台输出配置
CONSOLE_OUTPUT: Final[bool] = os.getenv('CONSOLE_OUTPUT', 'true').lower() == 'true'
CONSOLE_LOG_LEVEL: Final[str] = os.getenv('CONSOLE_LOG_LEVEL', 'INFO').upper()

# 文件输出配置
FILE_OUTPUT: Final[bool] = os.getenv('FILE_OUTPUT', 'true').lower() == 'true'
FILE_LOG_LEVEL: Final[str] = os.getenv('FILE_LOG_LEVEL', 'DEBUG').upper()

# 日志轮转配置
LOG_ROTATION_ENABLED: Final[bool] = os.getenv('LOG_ROTATION_ENABLED', 'true').lower() == 'true'
LOG_ROTATION_INTERVAL: Final[str] = os.getenv('LOG_ROTATION_INTERVAL', 'midnight')  # midnight, hourly, daily, weekly

# 调用位置配置
CALL_LOCATION_ENABLED: Final[bool] = os.getenv('CALL_LOCATION_ENABLED', 'true').lower() == 'true'
CALL_LOCATION_DEPTH: Final[int] = int(os.getenv('CALL_LOCATION_DEPTH', '3'))

# 异步配置
ASYNC_ENABLED: Final[bool] = os.getenv('ASYNC_ENABLED', 'true').lower() == 'true'
ASYNC_QUEUE_SIZE: Final[int] = int(os.getenv('ASYNC_QUEUE_SIZE', '1000'))
ASYNC_WORKER_THREADS: Final[int] = int(os.getenv('ASYNC_WORKER_THREADS', '2'))

# 异常处理配置
EXCEPTION_TRACE_ENABLED: Final[bool] = os.getenv('EXCEPTION_TRACE_ENABLED', 'true').lower() == 'true'
EXCEPTION_DETAIL_ENABLED: Final[bool] = os.getenv('EXCEPTION_DETAIL_ENABLED', 'true').lower() == 'true'

# 性能配置
PERFORMANCE_MONITORING: Final[bool] = os.getenv('PERFORMANCE_MONITORING', 'false').lower() == 'true'
PERFORMANCE_THRESHOLD_MS: Final[int] = int(os.getenv('PERFORMANCE_THRESHOLD_MS', '100'))

# 安全配置
SENSITIVE_DATA_FILTER: Final[bool] = os.getenv('SENSITIVE_DATA_FILTER', 'true').lower() == 'true'
SENSITIVE_PATTERNS: Final[str] = os.getenv('SENSITIVE_PATTERNS', 'password,token,secret,key')

# 类型定义
LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]

# 环境变量映射
ENVIRONMENT_CONFIG: Final[Dict[str, str]] = {
    'development': 'DEBUG',
    'testing': 'DEBUG',
    'staging': 'INFO',
    'production': 'WARNING',
    'prod': 'WARNING'
}

def get_log_level() -> int:
    """从环境变量获取日志级别
    
    Returns:
        int: 日志级别对应的数值
    """
    # 优先使用 LOG_LEVEL
    env_level = os.getenv('LOG_LEVEL', '').upper()
    if env_level and env_level in LOG_LEVELS:
        return LOG_LEVELS[env_level]
    
    # 其次使用环境变量映射
    env = os.getenv('ENVIRONMENT', '').lower()
    if env in ENVIRONMENT_CONFIG:
        return LOG_LEVELS[ENVIRONMENT_CONFIG[env]]
    
    # 默认返回 INFO
    return LOG_LEVELS['INFO']

def get_file_size_bytes(size_str: str) -> int:
    """将文件大小字符串转换为字节数
    
    Args:
        size_str: 文件大小字符串，如 '100MB', '1GB'
        
    Returns:
        int: 字节数
    """
    size_str = size_str.upper()
    if size_str.endswith('KB'):
        return int(size_str[:-2]) * 1024
    elif size_str.endswith('MB'):
        return int(size_str[:-2]) * 1024 * 1024
    elif size_str.endswith('GB'):
        return int(size_str[:-2]) * 1024 * 1024 * 1024
    else:
        return int(size_str)

def get_sensitive_patterns() -> list[str]:
    """获取敏感数据过滤模式
    
    Returns:
        list[str]: 敏感数据模式列表
    """
    patterns = SENSITIVE_PATTERNS.split(',')
    return [pattern.strip() for pattern in patterns if pattern.strip()]

def update_log_level(level: LogLevel) -> None:
    """更新日志级别
    
    Args:
        level: 新的日志级别
    """
    os.environ['LOG_LEVEL'] = level

def get_config_summary() -> dict:
    """获取配置摘要信息
    
    Returns:
        dict: 配置摘要
    """
    return {
        'log_dir': LOG_DIR,
        'log_file': LOG_FILE,
        'log_level': get_log_level(),
        'console_output': CONSOLE_OUTPUT,
        'file_output': FILE_OUTPUT,
        'log_rotation': LOG_ROTATION_ENABLED,
        'async_enabled': ASYNC_ENABLED,
        'performance_monitoring': PERFORMANCE_MONITORING,
        'sensitive_filter': SENSITIVE_DATA_FILTER
    }
